package com.mao.shiro_jsp.realms;

import com.mao.shiro_jsp.cache.MyByteSource;
import com.mao.shiro_jsp.entity.Perms;
import com.mao.shiro_jsp.entity.User;
import com.mao.shiro_jsp.service.UserService;
import com.mao.shiro_jsp.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

/**
 * @author 小毛同学
 * @version 1.0
 * @data 2021/12/30 10:00
 */
public class CustomerRealm extends AuthorizingRealm {
    // 进行授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        // 从工厂中获取UserService对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        // 调用授权验证
        // 根据身份信息获取角色和权限信息
        User roles = userService.findRolesByUserName(primaryPrincipal);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if (roles != null){
            roles.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
                // 添加权限
                List<Perms> perms = userService.findPermsByRoleName(role.getName());
                perms.forEach(perm -> {
                    simpleAuthorizationInfo.addStringPermission(perm.getName());
                });
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        String principal = (String) Token.getPrincipal();  //获取凭证信息

        // 从工厂中获取UserService对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (user != null){
            return new SimpleAuthenticationInfo(user.getUsername(),
                    user.getPassword(),
                    new MyByteSource(user.getSalt()),
                    this.getName());
        }
        return null;
    }
}
